/*
 * @Date         : 2022-07-21 19:22:40
 * @LastEditors  : zu1662
 * @LastEditTime : 2024-05-24 14:59:55
 * @Description  : 阿里云OSS
 *
 * Copyright © 2022 by zu1662, All Rights Reserved.
 */
import OSS from 'ali-oss';
import { OssInfo } from '../oss.interface';
import { OssClient } from '../oss.client';

export class AliyunOssClient extends OssClient {
  constructor(config: OssInfo) {
    super(config);
    this.ossClient = new OSS({
      region: this.config.ossRegion,
      accessKeyId: this.config.ossAccessId,
      accessKeySecret: this.config.ossAccessSecret,
      bucket: this.config.ossBucket,
    });
  }

  async putFile(filename: string, buffer: ReadableStream<any>, options?: any): Promise<string> {
    const headers = {
      'x-oss-object-acl': 'public-read',
      ...options?.headers,
    };

    const result = await this.ossClient.put(filename, buffer, { headers });

    return result.url;
  }

  async deleteFile(filename: string): Promise<boolean> {
    try {
      await this.ossClient.delete(filename);
      return true;
    } catch (e) {
      return false;
    }
  }

  async deleteFiles(filenames: string[]): Promise<boolean> {
    try {
      await this.ossClient.deleteMulti(filenames);
      return true;
    } catch (e) {
      return false;
    }
  }
}
